<template>
  <div class="plant">
    <header>
      <BaseNavBar title="我的植物" :is-nav="true" />
    </header>
    <main class="plant_main">

      <Card v-for="item in plantList" :key="item?.id">
        <van-swipe-cell>
          <section class="plant_main_item" @click="handleLookDetail(item)">
            <section class="plant_main_item_img">
              <van-image width="100" height="100" :src="item?.cover" v-if="item?.cover" />
            </section>
            <section class="plant_main_item_info">
              <section class="plant_main_item_title">名称：{{ item?.nickname }}</section>
              <section class="plant_main_item_variety"> 种类：{{ item?.variety }}</section>
              <section class="plant_main_item_address"> 位置：{{ item?.address }}</section>
              <section class="plant_main_item_date"> 种植日期{{ item?.plantDate }}</section>
              <section class="plant_main_item_action">
                <van-button round type="primary" size="mini" color="#09BB07"
                  @click.stop="handleAddPlan(item)">添加养护计划</van-button>
              </section>
            </section>
          </section>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="handleDelete(item)" />
          </template>
        </van-swipe-cell>
      </Card>
    </main>

    <van-dialog v-model:show="show" title="添加养护计划" show-cancel-button @confirm="handleConfirm" @cancel="handleCancel">
      <van-form>
        <van-cell-group inset>
          <van-field v-model="formState.matterName" name="matterName" label="养护事项" placeholder="请选择养护事项"
            @click="show3 = true" />
          <van-field v-model="formState.planDate" name="planDate" label="计划日期" placeholder="请选择计划日期"
            @click="show1 = true" />
          <van-field v-model="formState.planTime" name="planTime" label="提醒时间" placeholder="请选择提醒时间"
            @click="show2 = true" />
          <van-field v-model="formState.remarks" name="remarks" label="备注" placeholder="请输入备注" />
        </van-cell-group>
      </van-form>
    </van-dialog>
    <van-popup v-model:show="show1" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-date-picker :min-date="new Date()" title="请选择计划日期" @confirm="handleDateConfirm" @cancel="show1 = false" />
    </van-popup>
    <van-popup v-model:show="show2" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-time-picker :columns-type="['hour', 'minute','second']" title="选择提醒时间" @confirm="handleTimeConfirm" @cancel="show2 = false" />
    </van-popup>
    <van-popup v-model:show="show3" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-picker title="养护事项" :columns="columns" @confirm="handleMatterConfirm" @cancel="show3 = false" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { showConfirmDialog, showToast } from 'vant';
import BaseNavBar from '@/components/BaseNavBar/index.vue';
import Card from '@/components/Card/index.vue';
import { getPlantList, deletePlant } from '@/apis/plant';
import { addPlan } from '@/apis/plan';


const router = useRouter();
const plantList = ref([]);

const show = ref(false);
const show1 = ref(false);
const show2 = ref(false);
const show3 = ref(false);

const formState = ref({
  plantId: "",
  matter: "",
  planDate: "",
  remarks: "",
  planTime: "",
  matterName:""
});

const columns = [
  { text: '浇水', value: 1 },
  { text: '施肥', value: 2 },
  { text: '光照调整', value: 3 },
  { text: '修剪', value: 4 },
  { text: '病虫防治', value: 5 },
  { text: '换盆', value: 6 },
];



const init = async () => {
  try {
    const res = await getPlantList();
    if (res?.code === 200) {
      plantList.value = res?.data?.list;

    }
  } catch (error) {
    console.log(error, 'plant-list-error');

  }
};

const handleDelete = (item) => {
  showConfirmDialog({
    title: '温馨提示',
    message:
      '确定要删除该植物吗？',
  })
    .then(async () => {
      try {
        const res = await deletePlant(item?.id);
        if (res?.code === 200) {
          init();
          showToast.success('删除成功');
        }
      } catch (error) {
        console.log(error, 'delete-error');

      }
    })
    .catch(() => {
      // on cancel
    });
};

const handleLookDetail = (item) => {
  router.push(`/plant/detail/${item?.id}`);
};

const handleAddPlan = (item) => {
  show.value = true;
  formState.value.plantId = item?.id;
}

const handleConfirm = async () => {
  try {
    const res = await addPlan(formState.value);
    if(res?.code === 200){
      showToast('添加成功');
      formState.value = {};
    }
  } catch (error) {
    console.log(error, 'add-plan-error');

  }
};

const handleCancel = () => {
  show1.value = false;
  formState.value = {};
};

const handleDateConfirm = ({ selectedValues = [] }) => {
  formState.value.planDate = selectedValues?.join('-');
  show1.value = false;
};

const handleTimeConfirm = ({ selectedValues = [] }) => {
  formState.value.planTime = selectedValues?.join(':');
  show2.value = false;
}
const handleMatterConfirm = ({ selectedOptions = [] }) => {
  formState.value.matter = selectedOptions?.[0]?.value;
  formState.value.matterName = selectedOptions?.[0]?.text;
  show3.value = false;

}
onMounted(() => {
  init();
})
</script>

<style lang="less" scoped>
.plant {
  &_main {
    margin-top: 8px;

    &_item {
      margin-top: 8px;
      box-sizing: border-box;
      padding: 8px;
      display: flex;

      &_info {
        margin-left: 8px;
      }

      &_title {
        font-size: 16px;
        color: #333;
      }

      &_variety,
      &_address,
      &_date {
        font-size: 14px;
        color: #999;
      }
    }
  }
}

.delete-button {
  height: 100%;
}
</style>
